package com.yifeng.filter;


import com.yifeng.util.JwtUtil;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")

public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求路径
        String url = request.getRequestURL().toString();
        System.out.println("请求路径:" + url);

        // 判断是否是登录注册请求
        if (!url.contains("admin") || url.contains("adminHome")) {
            System.out.println("无需登录场景,直接放行");
            filterChain.doFilter(request, response);
            return;
        }

        // 获取token
        String token = request.getHeader("Authorization");
        System.out.println("token:" + token);

        // 判断token是否存在
        if (token == null || token.isEmpty()) {
            System.out.println("token为空或长度为0");
            response.setStatus(401);
        }

        // 判断token是否正确
        Claims claims;
        try {
            claims = JwtUtil.parseToken(token);
        } catch (Exception e) {
            System.out.println("token解析错误");
            response.setStatus(401);
            return;
        }

        // 检查是否访问admin路径
        if (url.contains("/admin")) {
            // 获取用户角色
            String role = claims.get("role") != null ? claims.get("role").toString() : null;

            // 只有admin角色才能访问
            if (!"admin".equals(role)) {
                System.out.println("非管理员用户尝试访问admin路径");
                response.setStatus(403); // 禁止访问
                return;
            }
        }
        // 放行
        filterChain.doFilter(request, response);
        System.out.println("放行");

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void destroy() {}
}
